package com.mrd.gtimp.order.action;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.mrd.base.Jqgrid;
import com.mrd.gtimpframe.entity.CustomCompanyInfo;
import com.mrd.gtimpframe.entity.Dictionary;
import com.mrd.gtimpframe.repository.CusInfoMapper;
import com.mrd.gtimpframe.service.DictionaryService;
import com.mrd.gtimpframe.service.impl.CusInfoServiceImpl;
import com.mrd.util.FormBeanUtil;
import com.mrd.util.LoginUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.mrd.exception.QueryException;
import com.mrd.gtimp.base.entity.Company;
import com.mrd.gtimp.base.service.CompanyBiz;
import com.mrd.gtimp.base.service.SystemValueBiz;
import com.mrd.gtimp.business.entity.DeclarationOffer;
import com.mrd.gtimp.business.entity.GoodsCode;
import com.mrd.gtimp.business.service.CompanyQpBiz;
import com.mrd.gtimp.business.service.DeclarationOfferBiz;
import com.mrd.gtimp.business.service.GoodsCodeBiz;
import com.mrd.gtimp.order.entity.OrderDropdownRecords;
import com.mrd.gtimpframe.repository.ResultNopassRefMapper;
import com.mrd.gtimpframe.service.ProtocolService;
import com.mrd.gtimpframe.service.TGenSupSrvProvideService;

/**
 * Created by lenovo on 2016/9/6. 在线下单下拉框数据
 */
@Controller
@RequestMapping("/order-dropdown")
public class OrderDropdownAction {
  private static final Logger logger = LoggerFactory.getLogger(OrderDropdownAction.class);
  @Resource
  private DeclarationOfferBiz declarationOfferBiz;
  @Resource
  private SystemValueBiz systemValueBiz;
  @Resource
  private CompanyQpBiz companyQpBiz;
  @Resource
  private GoodsCodeBiz goodsCodeBiz;
  @Resource
  private CompanyBiz companyBiz;

  @Resource
  private ResultNopassRefMapper resultNopassRefMapper;

  @Autowired
  private TGenSupSrvProvideService tGenSupSrvProvideService;
  @Resource
  private ProtocolService protocolService;
  @Resource
  private CusInfoServiceImpl cusInfoService;
  @Resource
  private DictionaryService dictionaryService;
  @Resource
  private CusInfoMapper cusInfoMapper;

  @RequestMapping("/noPassReasonByKey")
  @ResponseBody
  public DropdownResults noPassReasonByKey(String key) {
    PageOrder pageOrder = new PageOrder();
    pageOrder.setRows(100);
    pageOrder.setPage(0);
    DropdownResults dropdownResults = new DropdownResults();
    Map<String, Object> params = new HashedMap();
    params.put("dictionaryName", key);
    List<Map<String, Object>> reasonDropDown = resultNopassRefMapper.noPassReasonDropDown(params);
    for (Map<String, Object> map : reasonDropDown) {
      DropdownResult result = new DropdownResult(map.get("DICTIONARY_CODE").toString(),
              map.get("DICTIONARY_NAME").toString());
      dropdownResults.add(result);
    }
    return dropdownResults;
  }


  @RequestMapping("/cusCompanyByKey")
  @ResponseBody
  public DropdownResults cusCompanyByKey(String key) {
    PageOrder pageOrder = new PageOrder();
    pageOrder.setRows(100);
    pageOrder.setPage(0);
    DropdownResults dropdownResults = new DropdownResults();
    try {
      List<JSONObject> com = companyBiz.cusCompanyByKey(pageOrder.createPage(), key);
      for (JSONObject c : com) {
        DropdownResult result = new DropdownResult(c.getString("id"), c.getString("name"));
        dropdownResults.add(result);
      }
    } catch (QueryException e) {
      logger.error("下拉框查询客户信息出错!", e);
      dropdownResults.setSuccess("false");
    }
    return dropdownResults;
  }

  @RequestMapping("/supCompanyByKey")
  @ResponseBody
  public DropdownResults supCompanyByKey(String key) {
    PageOrder pageOrder = new PageOrder();
    pageOrder.setRows(100);
    pageOrder.setPage(0);
    DropdownResults dropdownResults = new DropdownResults();
    try {
      List<JSONObject> com = companyBiz.supCompanyByKey(pageOrder.createPage(), key);
      for (JSONObject c : com) {
        Map<String, String> map = new HashMap<>();
        map.put("port", c.getString("port"));
        map.put("port_code", c.getString("port_code"));
        map.put("com_customs_code", c.getString("com_customs_code"));
        DropdownResult result = new DropdownResult(c.getString("id"), c.getString("name"));
        result.setData(map);
        dropdownResults.add(result);
      }
    } catch (QueryException e) {
      logger.error("下拉框查询供应商信息出错!", e);
      dropdownResults.setSuccess("false");
    }
    return dropdownResults;
  }

  /**
   * 供应商
   */
  @RequestMapping("/supCompany")
  @ResponseBody
  public DropdownResults supCompany(boolean isExport, boolean isCCI, String code) {
    PageOrder pageOrder = new PageOrder();
    pageOrder.setRows(100);
    pageOrder.setPage(0);
    DropdownResults dropdownResults = new DropdownResults();
    try {
      List<Map<String, Object>> com = protocolService.getHaveEftProtocolCompany(isExport, isCCI);
      for (Map<String, Object> c : com) {
        String portCode = c.get("PORT_CODE") + "";
        if(code != null && !portCode.contains(code)){
          continue;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("port", c.get("PORT"));
        map.put("port_code", portCode);
        map.put("com_customs_code", c.get("COM_CUSTOMS_CODE"));
        map.put("hasSO", c.get("HAS_SO"));
        // map.put("amount", c.getString("amount"));
        // map.put("container_amount", c.getString("container_amount"));
        DropdownResult result = new DropdownResult(c.get("COM_ID").toString(), c.get("COM_NAME").toString());
        result.setData(map);
        dropdownResults.add(result);
      }
    } catch (Exception e) {
      logger.error("下拉框查询供应商信息出错!", e);
      dropdownResults.setSuccess("false");
      e.printStackTrace();
    }
    return dropdownResults;
  }

  /**
   * 供应商
   */
  @RequestMapping("/tgyihSupCompany")
  @ResponseBody
  public DropdownResults tgythCompany(String isTongguanYth, String code) {
    PageOrder pageOrder = new PageOrder();
    pageOrder.setRows(100);
    pageOrder.setPage(0);
    DropdownResults dropdownResults = new DropdownResults();
    try {
      List<JSONObject> com = null;
      if (isTongguanYth.equals("1")) {
        com = tGenSupSrvProvideService.selOffLineCompany("");
      } else {
        com = companyBiz.supCom(pageOrder.createPage(), false, code);
      }
      for (JSONObject c : com) {
        Map<String, String> map = new HashMap<>();
        map.put("port", c.getString("port"));
        map.put("port_code", c.getString("port_code"));
        map.put("com_customs_code", c.getString("com_customs_code"));
        map.put("hasSO", c.getString("hasSO"));
        // map.put("amount", c.getString("amount"));
        // map.put("container_amount", c.getString("container_amount"));
        DropdownResult result = new DropdownResult(c.getString("port_code"), c.getString("port"));
        result.setData(map);
        dropdownResults.add(result);
      }
    } catch (QueryException e) {
      logger.error("下拉框查询供应商信息出错!", e);
      dropdownResults.setSuccess("false");
    } catch (Exception e) {
      e.printStackTrace();
    }
    return dropdownResults;
  }

  /**
   * 收发货人 消费使用单位 申报单位
   *
   * @param key 过滤字段
   */
  @RequestMapping("/company")
  @ResponseBody
  public DropdownResults company(String key) {
    PageOrder pageOrder = new PageOrder();
    pageOrder.setRows(15);
    DropdownResults dropdownResults = new DropdownResults();
    try {
      String[][] cc = companyQpBiz.findCompanyByCodes(key, pageOrder.createPage());
      for (String[] str : cc) {
        String label = "0".equals(str[6])
                ? MessageFormat.format("<div style='color:blue'>{0}    (未验证)<br />{1}</div>", str[1],
                str[0])
                : MessageFormat.format("{0}<br />{1}", str[1], str[0]);
        DropdownResult result = new DropdownResult(str[1], label, str[0]);
        Map<String, Object> dataMap = new HashedMap();
        String com=str[5];
        if (StringUtils.isNotEmpty(str[5]) && !"null".equals(str[5])) {
          dataMap.put("company_co_unite", str[5]);
          result.setData(dataMap);
        }
        dropdownResults.add(result);
      }
    } catch (Exception e) {
      logger.error("下拉框查询供应商信息出错!", e);
      dropdownResults.setSuccess("false");
    }
    return dropdownResults;
  }
  /**
   * 代录人公司客户列表
   *
   */
  @RequestMapping("/getComName")
  @ResponseBody
  public DropdownResults getCompanyNameList(String key,Jqgrid jqgrid) {
    DropdownResults dropdownResults = new DropdownResults();
    try {
      String comInfoId = LoginUtil.getLoginUser().getCompany().getId();
      CustomCompanyInfo params = FormBeanUtil.getEntityFromJqgrid(jqgrid, CustomCompanyInfo.class);
      params.setComInfoId(comInfoId);
      params.setName(key);
      List<CustomCompanyInfo> customCompanyInfos = cusInfoService.selectSelectiveCompId(params);
      for (CustomCompanyInfo companyInfo : customCompanyInfos) {
        DropdownResult result = new DropdownResult(companyInfo.getName(), companyInfo.getName(), companyInfo.getName());
        Map<String,String> map=new HashMap<>();
        map.put("comInfoId",companyInfo.getComInfoId());
        map.put("comName",companyInfo.getName());
        result.setData(map);
        dropdownResults.add(result);
      }
    } catch (Exception e) {
      logger.error("下拉查询公司出错!", e);
      dropdownResults.setSuccess("false");
    }
    return dropdownResults;
  }

  /**
   * 商品编号
   *
   * @param key 过滤值
   */
  @RequestMapping("/goods-code")
  @ResponseBody
  public DropdownResults goodsCode(String key) {
    PageOrder pageOrder = new PageOrder();
    pageOrder.setRows(15);
    DropdownResults dropdownResults = new DropdownResults();
    try {
      Page<GoodsCode> list = goodsCodeBiz.findGoodCode(key, pageOrder.createPage());
      for (GoodsCode good : list.getContent()) {
        DropdownResult result = dropdownResults
                .add(new DropdownResult(good.getCODE_T(), MessageFormat.format("({0}.{1}){2}",
                        good.getCODE_T(), good.getCODE_S(), good.getG_NAME()), good.getG_NAME()));
        Map<String, String> map = new HashMap<>();
        map.put("code_t", good.getCODE_T());
        map.put("unit1", good.getUNIT_1());
        map.put("unit2", good.getUNIT_2());
        map.put("code_s", good.getCODE_S());
        map.put("name", good.getG_NAME());
        map.put("good_mode", good.getGOODS_MODE());
        result.setData(map);
      }
    } catch (QueryException e) {
      e.printStackTrace();
    }

    return dropdownResults;
  }
  /**
   * 代录单客户公司下拉列表
   *
   * @param key 过滤值
   */
  @RequestMapping("/custComList")
  @ResponseBody
  public DropdownResults custComList(String key) {
    DropdownResults dropdownResults = new DropdownResults();
    try{
      String comId=LoginUtil.getLoginUser().getCompany().getId();
      CustomCompanyInfo customCompanyInfo=new CustomCompanyInfo();
      customCompanyInfo.setComInfoId(comId);
      customCompanyInfo.setName(key);
      List<CustomCompanyInfo> list = cusInfoMapper.selectSelectiveCompId(customCompanyInfo);
      for (CustomCompanyInfo customCompanyInfo1 : list) {
        DropdownResult result = new DropdownResult(customCompanyInfo1.getComInfoId(),customCompanyInfo1.getName(),customCompanyInfo1.getName());
        Map<String, String> map = new HashMap<>();
        map.put("agent_for_com_id", customCompanyInfo1.getComInfoId());
        map.put("agent_name", customCompanyInfo1.getName());
        result.setData(map);
        dropdownResults.add(result);
      }
      return dropdownResults;
    }catch (Exception e){
      e.printStackTrace();
    }
    return  dropdownResults;
  }

  /**
   * 以下废弃
   */
  /**
   * 商品下拉框关联 第一计算单位信息
   *
   * @param linkKeyVal 第一计算单位
   */
  @RequestMapping(path = "/baseData_linkData", params = "linkTable=hg_co_jldw")
  @ResponseBody
  public OrderDropdownRecords goodDownUnit1(@RequestParam(required = false) String linkKeyVal)
          throws QueryException {
    OrderDropdownRecords orderDropdownRecords = new OrderDropdownRecords();
    String[][] unit = systemValueBiz.findUnits1(linkKeyVal);
    return resultNnit1(unit, orderDropdownRecords);
  }

  // 返回商品下拉框关联 第一计算单位信息结果
  public OrderDropdownRecords resultNnit1(String[][] unit,
                                          OrderDropdownRecords orderDropdownRecords) {
    for (String[] str : unit) {
      Map<String, String> map = new HashMap<>();
      map.put("ID", str[1].toString());
      map.put("HGDM", str[0].toString());
      map.put("HGSM", str[1].toString());
      map.put("SHOWNAME", "(" + str[1].toString() + ")" + str[0].toString());
      orderDropdownRecords.add(map);
    }
    return orderDropdownRecords;
  }

  /**
   * 商品下拉框关联 第一计算单位信息
   *
   * @param linkKeyVal 第一计算单位
   */
  @RequestMapping(path = "/baseData_linkData", params = "linkTable=co_sphsbm")
  @ResponseBody
  public OrderDropdownRecords goodUnit1(@RequestParam(required = false) String linkKeyVal,
                                        Pageable pageable) throws QueryException {
    return goodResult(linkKeyVal, pageable);

  }

  /**
   * 商品选中关联 第一计算单位信息
   */
  @RequestMapping(path = "/gqdm", params = "table=co_sphsbm")
  @ResponseBody
  public OrderDropdownRecords findGoodOfCodeBy(@RequestParam(required = false) String keyword,
                                               Pageable pageable) throws QueryException {
    return goodResult(keyword, pageable);
  }

  // 返回商品信息结果
  private OrderDropdownRecords goodResult(String keyword, Pageable pageable) throws QueryException {
    OrderDropdownRecords dropdownRecords = new OrderDropdownRecords();
    Page<GoodsCode> list = goodsCodeBiz.findGoodCode(keyword, pageable);
    for (GoodsCode good : list.getContent()) {
      Map<String, String> map = new HashMap<>();
      map.put("ID", good.getCODE_T());
      map.put("HSCODE", good.getCODE_T());
      map.put("BZJFDW", good.getUNIT_1());
      map.put("CIQ_STD_MEASURE", good.getUNIT_1());// 第一计算单位
      map.put("MODEL", good.getCODE_S());
      map.put("HSNAME", good.getG_NAME());
      dropdownRecords.add(map);
    }
    return dropdownRecords;
  }

  /**
   * 供应商 报关行 （hg_gys_bgh）
   */
  @RequestMapping(path = "/gqdm", params = "table=hg_gys_bgh")
  @ResponseBody
  public OrderDropdownRecords supCompanys(PageOrder pageOrder) throws QueryException {
    OrderDropdownRecords orderDropdownRecords = new OrderDropdownRecords();
    List<Company> com = companyBiz.supCom(pageOrder.createPage());
    for (Company c : com) {
      Map<String, String> map = new HashMap<>();
      map.put("ID", c.getId());
      map.put("HGNAMECN", c.getName());
      orderDropdownRecords.add(map);
    }
    orderDropdownRecords.setTotal(com.size());
    return orderDropdownRecords;
  }

  /**
   * 申报 第二计量单位 （hg_co_jldw）
   */
  @RequestMapping(path = "/gqdm", params = "table=hg_co_jldw")
  @ResponseBody
  public OrderDropdownRecords unitSofme(PageOrder pageOrder) throws QueryException {
    OrderDropdownRecords orderDropdownRecords = new OrderDropdownRecords();
    String[][] unit = systemValueBiz.findUnitsOfMeasurementby(pageOrder.createPage());
    for (String[] str : unit) {
      Map<String, String> map = new HashMap<>();
      map.put("ID", str[1].toString());
      map.put("GQDM", str[0].toString());
      map.put("GQJC", str[1].toString());
      map.put("SHOWNAME", "(" + str[1].toString() + ")" + str[0].toString());
      orderDropdownRecords.add(map);
    }
    orderDropdownRecords.setTotal(unit.length);
    return orderDropdownRecords;
  }

  /**
   * 1.收发货人 2.消费使用单位 （hg_option）
   */
  @RequestMapping(path = "/gqdm", params = "table=hg_option")
  @ResponseBody
  public OrderDropdownRecords companys(@RequestParam(required = false) String keyword,
                                       PageOrder pageOrder) throws QueryException {
    OrderDropdownRecords orderDropdownRecords = new OrderDropdownRecords();
    String[][] findcc = companyQpBiz.findCompanyByCodes(keyword, pageOrder.createPage());
    orderDropdownRecords.setTotal(findcc.length);
    for (String[] str : findcc) {
      Map<String, String> map = new HashMap<>();
      map.put("id", str[1].toString());
      map.put("HGNAMECN", str[0].toString()); // 公司名称
      map.put("HGCODE", str[1].toString());
      orderDropdownRecords.add(map);
    }
    return orderDropdownRecords;
  }

  /**
   * 海关申报-货场代码 （co_hghcdm）
   */
  @RequestMapping(path = "/gqdm", params = "table=co_hghcdm")
  @ResponseBody
  public OrderDropdownRecords findHgdata(@RequestParam(required = false) String keyword,
                                         Pageable pageable) throws QueryException {
    OrderDropdownRecords orderDropdownRecords = new OrderDropdownRecords();
    List<DeclarationOffer> declarationOffers =
            declarationOfferBiz.findOfferPortWithCode(keyword, pageable);
    Page<DeclarationOffer> page = new PageImpl<>(declarationOffers);
    orderDropdownRecords.setTotal(page.getSize());
    for (DeclarationOffer declarationOffer : page.getContent()) {
      Map<String, String> map = new HashMap<>();
      map.put("ID", declarationOffer.getPort_code());
      map.put("DM", declarationOffer.getPort_code());
      // map.put("SSGQ", );
      map.put("MC", declarationOffer.getPort());
      map.put("SHOWNAME", "(" + declarationOffer.getPort_code() + ")" + declarationOffer.getPort());
      orderDropdownRecords.add(map);
    }
    return orderDropdownRecords;
  }

    /**
     * 代录单费用协议适用客户下拉
     */
    @RequestMapping("/platformFeeCustomer")
    @ResponseBody
    public DropdownResults platformFeeCustomer(String key) {
        DropdownResults dropdownResults = this.cusCompanyByKey(key);
//        dropdownResults.add(new DropdownResult("ALL", "全部"));
        return dropdownResults;
    }

    /**
     * 公司类型下拉
     */
    @RequestMapping("/getCompanyType")
    @ResponseBody
    public DropdownResults getCompanyType() {
        return this.getFromDictionry("EFT_CUST_COM_TYPE");
    }

    /**
     * 费用规则下拉
     */
    @RequestMapping("/getChargeMode")
    @ResponseBody
    public DropdownResults getChargeMode() {
        return this.getFromDictionry("protocol_count_fee_rule");
    }

    /**
     * 委托关系下拉
     */
    @RequestMapping("/getAgentSelf")
    @ResponseBody
    public DropdownResults getAgentSelf() {
        return this.getFromDictionry("EFT_CUST_AGENT_SELF");
    }

    private DropdownResults getFromDictionry(String groupCode) {
        if (groupCode == null) {
            return null;
        }
        DropdownResults dropdownResults = new DropdownResults();
        List<Dictionary> dictionaryList = dictionaryService.selectWithDictionaryByCodesIn(groupCode);
        if (dictionaryList != null) {
            for (Dictionary dictionary : dictionaryList) {
                dropdownResults.add(new DropdownResult(dictionary.getDictionaryCode(), dictionary.getDictionaryName()));
            }
        }
        return dropdownResults;
    }

    /**
     * 下拉框分页
     */
    public static class PageOrder {

    public PageOrder() {}

    private int page = 1; // 第几页
    private int rows = 7;// 每一页显示多少条

    public int getRows() {
      return rows;
    }

    public void setRows(int rows) {
      this.rows = rows;
    }

    public int getPage() {
      return page;
    }

    public void setPage(int page) {
      this.page = page;
    }

    public Pageable createPage() {
      return new PageRequest(page, rows);
    }

  }
}


/**
 * semantic ui dropdown查询结果集
 */
class DropdownResults {
  static final String FETCH_SUCCESS = "true";
  static final String FETCH_FAIL = "true";
  private String success;
  private List<DropdownResult> results;

  public DropdownResults() {
    this.success = FETCH_SUCCESS;
    this.results = new ArrayList<>();
  }

  public DropdownResult add(String value, String name) {
    DropdownResult result = new DropdownResult(value, name);
    add(result);
    return result;
  }

  public DropdownResult add(String value, String name, String text) {
    DropdownResult result = new DropdownResult(value, name, text);
    add(result);
    return result;
  }

  public DropdownResult add(DropdownResult result) {
    if (results == null) {
      results = new ArrayList<>();
    }
    results.add(result);
    return result;
  }

  public String getSuccess() {
    return success;
  }

  public void setSuccess(String success) {
    this.success = success;
  }

  public List<DropdownResult> getResults() {
    return results;
  }

  public void setResults(List<DropdownResult> results) {
    this.results = results;
  }
}


/**
 * semantic ui dropdown查询结果集
 */
class DropdownResult {
  /**
   * 真实值
   */
  private String value;
  /**
   * 显示在下拉框中的值
   */
  private String name;
  /**
   * 选择的值
   */
  private String text;
  /**
   * 附加值
   */
  private Object data;

  public DropdownResult(String value, String name) {
    this.value = value;
    this.name = name;
  }

  public DropdownResult(String value, String name, String text) {
    this.value = value;
    this.name = name;
    this.text = text;
  }

  public String getValue() {
    return value;
  }

  public void setValue(String value) {
    this.value = value;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getText() {
    return text;
  }

  public void setText(String text) {
    this.text = text;
  }

  public Object getData() {
    return data;
  }

  public void setData(Object data) {
    this.data = data;
  }
}
